// pages/order/index.js
const app = getApp();

import {
  getOrderList,
  getPackageList
} from '../../api/order';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    active: 0, //当前激活的标签页
    orders: [], //全部订单
    products: [], //商品列表
    orderState: ["待付款", "已支付", "已完成", "已取消"], //订单状态
    pendingPayment: [], //待付款
    pendingService: [], //待服务
    completed: [], //已完成
    canceled: [], //已取消
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 取传入的 state，默认为 0
    const state = options.state ? Number(options.state) : 0;
    this.setData({
      active: state,
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getList();
  },

  /**
   * 获取订单和商品列表
   */
  async getList() {
    try {
      const [orderRes, productRes] = await Promise.all([
        getOrderList(),
        getPackageList()
      ]);
      const orders = orderRes.data || [];
      // 商品列表转为对象，key为字符串类型的packageId
      const productsArr = productRes.data || [];
      const products = {};
      productsArr.forEach((item) => {
        products[String(item.id)] = item;
      });
      // 分类映射
      const orderMap = {
        pendingPayment: [],
        pendingService: [],
        completed: [],
        canceled: [],
      };
      orders.forEach((item) => {
        if (item.state === 0) orderMap.pendingPayment.push(item);
        else if (item.state === 1) orderMap.pendingService.push(item);
        else if (item.state === 2) orderMap.completed.push(item);
        else if (item.state === 3) orderMap.canceled.push(item);
      });

      this.setData({
        orders,
        products, // 这里是对象，key为字符串
        ...orderMap,
      });
    } catch (err) {
      wx.showToast({
        title: "加载失败",
        icon: "none"
      });
      console.error("获取订单或商品失败", err);
    }
  },

  /**
   * 跳转订单详情页
   * @param {*} e
   */
  handleClick: function (e) {
    const detail_index = e.currentTarget.dataset.id;
    let currentList = [];
    // 根据 active 判断当前 tab 对应的订单数组
    if (this.data.active === 0) currentList = this.data.pendingPayment;
    else if (this.data.active === 1) currentList = this.data.pendingService;
    else if (this.data.active === 2) currentList = this.data.completed;
    else if (this.data.active === 3) currentList = this.data.canceled;
    const order = currentList[detail_index];
    console.log(order);
    wx.navigateTo({
      url: "/pages/orderDetails/index?orderId=" + order.id + "&state=" + this.data.active,
    });
  },

  onChange(event) {
    // event.detail.index 是当前激活 tab 的索引
    this.setData({
      active: event.detail.index,
    });
    console.log("switch to tab" + event.detail.index)
  },
});